package com.doubi.controller.api;

import cn.hutool.core.util.IdUtil;
import com.doubi.AliyunOssUtil;
import com.doubi.utils.DataUtil;
import com.doubi.vo.AliyunSTS;
import com.doubi.vo.AppUiModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("Api")
@Api(value = "文件上传模块", tags = "文件上传模块")
public class ApiUploadController {
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    /**
     * 文件上传
     */
    @ApiOperation(value = "获取token")
    @GetMapping("/GetOssToken")
    public AppUiModel<AliyunSTS> getUploadToken() {
        return new AppUiModel<>(aliyunOssUtil.getSTSToken());
    }


    /**
     * 文件上传
     */
    @ApiOperation(value = "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file"),
    })
    @GetMapping("/uploadFile")
    public AppUiModel<String> uploadFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            /*
             * 修改文件名称并保存文件
             */
            if (DataUtil.isEmpty(fileName)) {
                return new AppUiModel<>(400, "上传错误！");
            }
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String uuid = IdUtil.simpleUUID();
            fileName = uuid + suffix;
            /*
             * 入阿里云
             */
            return new AppUiModel<>(aliyunOssUtil.upload(file.getInputStream(), fileName));
        } catch (Exception e) {
            return new AppUiModel<>(400, "上传出错！");
        }
    }
}
